import { DeliveryRecord, PluginSettings, PluginState } from '@/types';

// 默认设置
export const DEFAULT_SETTINGS: PluginSettings = {
  dailyLimit: 50,
  deliveryInterval: 3,
  autoScroll: true,
  blacklistCompanies: [],
  filterKeywords: [],
  deliveryMessage: '您好，我对这个职位很感兴趣，希望能有机会详细了解。'
};

// 默认状态
export const DEFAULT_STATE: PluginState = {
  isRunning: false,
  isPaused: false,
  todayDeliveryCount: 0,
  totalDeliveryCount: 0,
  currentPage: 1
};

// 存储键名
export const STORAGE_KEYS = {
  SETTINGS: 'boss_auto_delivery_settings',
  STATE: 'boss_auto_delivery_state',
  RECORDS: 'boss_auto_delivery_records',
  DAILY_COUNT: 'boss_auto_delivery_daily_count'
};

// 获取设置
export async function getSettings(): Promise<PluginSettings> {
  const result = await chrome.storage.local.get(STORAGE_KEYS.SETTINGS);
  return { ...DEFAULT_SETTINGS, ...result[STORAGE_KEYS.SETTINGS] };
}

// 保存设置
export async function saveSettings(settings: PluginSettings): Promise<void> {
  await chrome.storage.local.set({ [STORAGE_KEYS.SETTINGS]: settings });
}

// 获取状态
export async function getState(): Promise<PluginState> {
  const result = await chrome.storage.local.get(STORAGE_KEYS.STATE);
  return { ...DEFAULT_STATE, ...result[STORAGE_KEYS.STATE] };
}

// 保存状态
export async function saveState(state: PluginState): Promise<void> {
  await chrome.storage.local.set({ [STORAGE_KEYS.STATE]: state });
}

// 获取投递记录
export async function getDeliveryRecords(): Promise<DeliveryRecord[]> {
  const result = await chrome.storage.local.get(STORAGE_KEYS.RECORDS);
  return result[STORAGE_KEYS.RECORDS] || [];
}

// 添加投递记录
export async function addDeliveryRecord(record: DeliveryRecord): Promise<void> {
  const records = await getDeliveryRecords();
  records.unshift(record);
  // 只保留最近1000条记录
  if (records.length > 1000) {
    records.splice(1000);
  }
  await chrome.storage.local.set({ [STORAGE_KEYS.RECORDS]: records });
}

// 检查今日投递数量
export async function getTodayDeliveryCount(): Promise<number> {
  const today = new Date().toDateString();
  const result = await chrome.storage.local.get(STORAGE_KEYS.DAILY_COUNT);
  const dailyData = result[STORAGE_KEYS.DAILY_COUNT] || {};
  return dailyData[today] || 0;
}

// 增加今日投递数量
export async function incrementTodayCount(): Promise<number> {
  const today = new Date().toDateString();
  const result = await chrome.storage.local.get(STORAGE_KEYS.DAILY_COUNT);
  const dailyData = result[STORAGE_KEYS.DAILY_COUNT] || {};
  dailyData[today] = (dailyData[today] || 0) + 1;
  
  // 清理7天前的数据
  const sevenDaysAgo = new Date();
  sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
  Object.keys(dailyData).forEach(date => {
    if (new Date(date) < sevenDaysAgo) {
      delete dailyData[date];
    }
  });
  
  await chrome.storage.local.set({ [STORAGE_KEYS.DAILY_COUNT]: dailyData });
  return dailyData[today];
}